import request from '@/utils/request'
import { validateExcelFile } from '@/utils/request'
import type { ApiResponse, UserDTO, PageResponse } from '@/types/api'
import { ElMessage, ElMessageBox } from 'element-plus'

interface UserQueryRequest {
  username?: string
  phone?: string
  email?: string
  status?: number
  deptId?: string
  current?: number
  size?: number
}

// 用户管理API
export const userApi = {
  // 创建用户
  createUser: (data: UserDTO): Promise<ApiResponse<UserDTO>> => {
    return request.post('/users', data)
  },

  // 更新用户信息
  updateUser: (userId: string, data: UserDTO): Promise<ApiResponse<UserDTO>> => {
    return request.put(`/users/${userId}`, data)
  },

  // 获取用户详情
  getUser: (userId: string): Promise<ApiResponse<UserDTO>> => {
    return request.get(`/users/${userId}`)
  },

  // 删除用户（软删除）
  deleteUser: (userId: string): Promise<ApiResponse<void>> => {
    return request.delete(`/users/${userId}`)
  },

  // 分页查询用户列表
  queryUsers: (params: UserQueryRequest): Promise<ApiResponse<PageResponse<UserDTO>>> => {
    return request.get('/users', { params })
  },

  // 启用用户
  enableUser: (userId: string): Promise<ApiResponse<void>> => {
    return request.put(`/users/${userId}/enable`)
  },

  // 禁用用户
  disableUser: (userId: string): Promise<ApiResponse<void>> => {
    return request.put(`/users/${userId}/disable`)
  },

  // 解锁用户
  unlockUser: (userId: string): Promise<ApiResponse<void>> => {
    return request.put(`/users/${userId}/unlock`)
  },

  // 重置用户密码
  resetUserPassword: (userId: string): Promise<ApiResponse<string>> => {
    return request.put(`/users/${userId}/reset-password`)
  },

  // 导出用户数据
  exportUsers: async (params: UserQueryRequest): Promise<void> => {
    return request.download({
      url: '/users/export',
      params,
      filename: `用户列表_${new Date().toISOString().slice(0, 10)}.xlsx`
    })
  },

  // 导入用户数据
  importUsers: (file: File, updateSupport: boolean = false): Promise<ApiResponse<{
    total: number
    successCount: number
    failureCount: number
    errorMessages: string[]
  }>> => {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('updateSupport', String(updateSupport))
    return request.upload({
      url: '/users/import',
      data: formData,
      showMessage: false  // 组件中会自定义显示导入结果
    })
  },

  // 下载导入模板
  downloadImportTemplate: async (): Promise<void> => {
    return request.download({
      url: '/users/template',
      filename: '用户导入模板.xlsx'
    })
  },

  // 获取用户统计信息
  getUserStatistics: (): Promise<ApiResponse<{
    totalUsers: number
    activeUsers: number
    disabledUsers: number
    lockedUsers: number
    newUsersThisMonth: number
  }>> => {
    return request.get('/users/statistics')
  },

  // 批量删除用户
  batchDeleteUsers: (userIds: string[]): Promise<ApiResponse<string>> => {
    return request.delete('/users/batch', { data: userIds })
  },

  // 批量启用用户
  batchEnableUsers: (userIds: string[]): Promise<ApiResponse<string>> => {
    return request.put('/users/batch/enable', userIds)
  },

  // 批量禁用用户
  batchDisableUsers: (userIds: string[]): Promise<ApiResponse<string>> => {
    return request.put('/users/batch/disable', userIds)
  }
}

// ==================== 高级封装函数（组件直接调用） ====================

/**
 * 导出用户（封装了所有业务逻辑）
 * @param params 查询参数
 * @example
 * await exportUsersWithUI(queryParams)
 */
export const exportUsersWithUI = async (params: UserQueryRequest): Promise<void> => {
  try {
    await userApi.exportUsers(params)
  } catch (error) {
    console.error('导出失败:', error)
  }
}

/**
 * 导入用户（封装了验证、上传、结果显示等所有逻辑）
 * @param file 文件对象
 * @param updateSupport 是否支持更新
 * @param onSuccess 导入成功回调（用于刷新列表）
 * @example
 * await importUsersWithUI(file, true, () => getList())
 */
export const importUsersWithUI = async (
  file: File | null,
  updateSupport: boolean,
  onSuccess?: () => void
): Promise<void> => {
  if (!file) {
    ElMessage.warning('请选择要导入的文件')
    return
  }

  // 验证文件
  const validation = validateExcelFile(file)
  if (!validation.valid) {
    ElMessage.error(validation.message!)
    return
  }

  try {
    ElMessage.info('正在导入用户数据...')
    
    const response = await userApi.importUsers(file, updateSupport)
    const result = response.data
    
    const successMsg = `导入完成！总计: ${result.total}, 成功: ${result.successCount}, 失败: ${result.failureCount}`
    
    if (result.failureCount > 0 && result.errorMessages.length > 0) {
      ElMessageBox.alert(
        `${successMsg}\n\n失败详情：\n${result.errorMessages.slice(0, 10).join('\n')}${result.errorMessages.length > 10 ? '\n...' : ''}`,
        '导入结果',
        { confirmButtonText: '确定', type: 'warning' }
      )
    } else {
      ElMessage.success(successMsg)
    }
    
    // 调用成功回调
    if (onSuccess) {
      onSuccess()
    }
  } catch (error) {
    console.error('导入失败:', error)
  }
}

/**
 * 下载导入模板
 * @example
 * await downloadUserTemplateWithUI()
 */
export const downloadUserTemplateWithUI = async (): Promise<void> => {
  try {
    await userApi.downloadImportTemplate()
  } catch (error) {
    console.error('下载模板失败:', error)
  }
}

// ==================== 用户角色管理API ====================

export const userRoleApi = {
  // 获取用户角色列表
  getUserRoles: (userId: string): Promise<ApiResponse<any[]>> => {
    return request.get(`/users/${userId}/roles`)
  },

  // 为用户分配角色
  assignRoles: (userId: string, roleIds: string[]): Promise<ApiResponse<void>> => {
    return request.post(`/users/${userId}/roles`, roleIds)
  },

  // 移除用户角色
  removeRoles: (userId: string, roleIds: string[]): Promise<ApiResponse<void>> => {
    return request.delete(`/users/${userId}/roles`, { data: roleIds })
  },

  // 同步用户角色（替换式分配）
  syncRoles: (userId: string, roleIds: string[]): Promise<ApiResponse<void>> => {
    return request.put(`/users/${userId}/roles`, roleIds)
  }
}

// ==================== 默认导出 ====================

export default userApi
